package com.rent.weixin.model;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * @Author zhang
 * @create 2021/7/19 15:24
 */
public class WxAccessToken implements Serializable {

    // wxToken
    private String access_token;
    // 过期时间 = 微信过期秒数 + 返回时间秒
    private Long expiresTime;

    // 两小时120分钟
    private static final Long DEFAULT_RELEASE = 120L;
    // 本地时间
    private final LocalDateTime lastUseTime;

    public WxAccessToken() {
        this.lastUseTime = LocalDateTime.now();
    }

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    public void setExpires_in(long expires_in) {
        // 微信返回过期秒数
        long currentMillis = System.currentTimeMillis();
        // 获取过期秒数 - 30秒 转化成毫秒
        this.expiresTime = currentMillis + (expires_in - 30) * 1000L;
    }

    // 默认过期时间120分钟
    public boolean isExpired() {
        if (this.expiresTime == null) {
            return !LocalDateTime.now().isBefore(this.lastUseTime.plusMinutes(DEFAULT_RELEASE));
        }
        long currentMillis = System.currentTimeMillis();
        return currentMillis > this.expiresTime;
    }
    // 更新token
    public synchronized void updateAccessToken(String accessToken, long expiresInSeconds) {
        this.access_token = accessToken;
        long currentMillis = System.currentTimeMillis();
        // 获取过期秒数 - 30秒 转化成毫秒
        this.expiresTime = currentMillis + (expiresInSeconds - 30) * 1000L;
    }


}
